package C046;

import java.util.HashMap;

/**
 * ClassName: C06
 * Package: C046
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/8 17:30
 * @Version 1.0
 * @Since 1.0
 */
public class C06 {
    public static void main(String[] args) {
        int[] arr = {3,1,4,2};
        System.out.println(minSubarray(arr, 6));
    }


    public static int minSubarray(int[] nums, int p) {
        // 获取nums的整余
        long sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        long mod = sum % p;
        if(mod == 0) {
            return 0;
        }

        // 构建余数map
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, -1); // 余数为0，最晚下标暂时为-1.
        int cur = 0;
        int midMod = 0;
        long find = 0;
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            cur = (cur + nums[i]) % p;
            midMod = (cur % p);
            find = (midMod + p - mod) % p;
            if(map.containsKey((int)find)) {
                ans = Math.min(ans, i - map.get((int)find));
            }
            map.put(cur, i);
        }

        return ans == nums.length ? -1 : ans;

    }
}
